/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.neiquan.neiquandemowithkf.application;

import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;

import com.baidu.mapapi.SDKInitializer;
import com.easemob.chat.EMChat;
import com.easemob.helpdeskdemo.HxHelper;
import com.easemob.helpdeskdemo.utils.HelpDeskPreferenceUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import net.neiquan.neiquandemowithkf.R;
import net.neiquan.neiquandemowithkf.entity.User;
import net.neiquan.neiquandemowithkf.utils.UserUtils;
import net.neiquanlib.utils.LogC;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.AppUtils;
import org.haitao.common.utils.FileUtils;
import org.haitao.common.utils.ToastUtil;

import java.io.File;


/**
 * 作者 : hjb
 * 时间 : 2016/4/25.
 */
public class MyApplication extends Application {

    public static MyApplication instance;
    private boolean isDebug;
    public User mUser;

    @Override
    public void onCreate() {
        MultiDex.install(this);
        super.onCreate();
        instance = this;
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        isDebug = true;// 设置开启日志,发布时请关闭日志
        AppLog.setDedug(isDebug);
        LogC.setDebug(isDebug);
        ToastUtil.init(instance);
        ToastUtil.setLayoutId(R.layout.toast_custom, R.id.txt_tips);
        FileUtils.setRootPathName("net.neiquan.app");
        initImageLoader(instance);
        initHx();
        printSign();
//        SDKInitializer.initialize(getApplicationContext());//百度地图
        try {
            mUser = UserUtils.getUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveUser(User user) {
        try {
            UserUtils.saveUser(instance, user);
            mUser = UserUtils.getUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initHx() {
        //代码中设置环信IM的Appkey
        String appkey = HelpDeskPreferenceUtils.getInstance(this).getSettingCustomerAppkey();
        EMChat.getInstance().setAppkey(appkey);
        // init demo helper
        HxHelper.getInstance().init(instance);
    }

    public static void setHxNickName(String account) {
        HelpDeskPreferenceUtils.getInstance(instance).setSettingCurrentNick(account);
    }

    public static void setHxAccount(String nickName) {
        HelpDeskPreferenceUtils.getInstance(instance).setSettingCustomerAccount(nickName);
    }

    /**
     * app的sha1和包名
     * 获取百度地图key时候可以用
     */
    private void printSign() {
        String packageName = AppUtils.getPackageName(this);
        LogC.e("------应用包名-----" + packageName);
        String sign = AppUtils.getSign(this, packageName);
        LogC.e("------应用签名，和新浪签名工具生成的值一样的------" + sign);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public boolean isLogin() {
        return mUser != null;
    }

    public static MyApplication getInstance() {
        return instance;
    }

    public static void initImageLoader(Context context) {
        // Create default options which will be used for every
        // displayImage(...) call if no options will be passed to this method
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
        File file = FileUtils.getImageFile();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 1) // default
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .memoryCache(new UsingFreqLimitedMemoryCache((int) (Runtime.getRuntime().maxMemory() / 8)))
                .memoryCacheSizePercentage(13) // default
                .defaultDisplayImageOptions(defaultOptions)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs() // Remove for release app 日志log
                .diskCache(new UnlimitedDiskCache(file)).build();
        ImageLoader.getInstance().init(config);
    }

    public void loginOut() {
        try {
            UserUtils.saveUser(instance, null);
            mUser = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
